package utils;

import cn.leancloud.LCObject;
import com.alibaba.fastjson2.JSON;
import data.ActionModel;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.stage.Stage;
import lombok.Getter;
import lombok.Setter;
import org.openqa.selenium.chrome.ChromeDriver;
import page.mainPage.MainPage;

import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class GlobalVar {
    public static ChromeDriver driver;
    public static FXMLLoader loader;
    // 需要上传到云上的全局数据
    @Setter
    @Getter
    private static Map<String, LCObject> lcGlobalMap;

    public static Stage getMainStage() {
        Parent parent = loader.getRoot();
        return (Stage) parent.getScene().getWindow();
    }

    public static MainPage getMainPage() {
        return loader.getController();
    }

    // 去除结尾的 7 个 null
    public static int getActionListSize() {
        return getMainPage().getActionListSize();
    }

    public static List<ActionModel> getActionList() {
        return getMainPage().getActionList();
    }

    public static <T> T getGlobalData(String key, Class<T> type) {
        LCObject lcObject = GlobalVar.getLcGlobalMap().get(key);
        if (lcObject == null) {
            return null;
        }
        try {
            Constructor<T> cr = type.getConstructor(type);
            return cr.newInstance(lcObject.get(Constant.DB.VALUE));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> List<T> getGlobalArrayData(String key, Class<T> type) {
        LCObject lcObject = GlobalVar.getLcGlobalMap().get(key);
        if (lcObject == null) {
            return new ArrayList<>();
        } else {
            return JSON.parseArray(JSON.toJSON(lcObject.get(Constant.DB.VALUE)).toString(), type);
        }
    }

    public static void setGlobalData(String key, Object value) {
        LCObject lcObject = lcGlobalMap.get(key);
        if (lcObject == null) {
            lcObject = DBUtils.newData(Constant.DB.GlOBAL_DATA);
            lcObject.put(Constant.DB.KEY, key);
            lcGlobalMap.put(key, lcObject);
        }
        lcObject.put(Constant.DB.VALUE, value);
    }

}
